package com.cxria.pattern.observer.func2

abstract class DnsServer extends Observable implements Observer{

    @Override
    void update(Observable observable, Object recorder) {
        recorder as Recorder
        if(isLocal(recorder)){
            recorder.ip = getIpAddress()
        } else {
            responsFormUpperServer(recorder)
        }
        sign(recorder)
    }

    void setUpperServer(DnsServer dnsServer){
        deleteObservers()
        addObserver(dnsServer)
    }

    private void responsFormUpperServer(Recorder recorder){
        setChanged()
        notifyObservers(recorder)
    }

    protected abstract void sign(Recorder recorder)

    protected abstract boolean isLocal(Recorder recorder)

    private String getIpAddress(){
        def rand = new Random()
        def address = new StringBuffer()
        (0..3).each {
            address << rand.nextInt(255)
            if(it != 3){
                address << '.'
            }
        }
        address
    }

}
